<template>
  <div>
    <ul class="treeRoot">
      <li v-for="(item,index) in list" :key="index">
        <p :class="['treeNode',(item.childen&&item.childen.length>0)?'treeGroup':'treeItem']" @click.self="handSelect(item.id)">
          <span>
            <input type="checkbox" :id="item.id" :value="item.id" v-model="selectList">
            <label :for="item.id">{{item.title + item.id}}</label>
          </span>
        </p>

        <div v-if="item.childen&&item.childen.length>0">
          <tree :class="{'treeGroupContainer':true,'treeCollaps':ifCollapse(item.id)}" :data="item.childen" :change="handleChange"
            v-on:sentDataToRoot="reseverData"></tree>
        </div>
      </li>
    </ul>
  </div>
</template>
<script>
  export default {
    name: "tree",
    components: {},
    props: {
      data: {
        type: Array,
        default: () => {
          return [];
        },
        required: true,
        validator: function (value) {
          return value instanceof Array;
        }
      },
      change: {
        type: Function
      }
    },
    data() {
      return {
        list: [],
        selectItem: null,
        collapseArray: [],
        selectList: []
      };
    },
    mounted() {
      this.list = this.$props.data;
      console.log(this);

    },
    methods: {
      ifCollapse(id) {
        return this.collapseArray.includes(id);
      },
      // 判断折叠
      handSelect(id) {
        console.log(id);
        this.selectItem = id;
        let index = this.collapseArray.indexOf(id);
        if (index === -1) {
          this.collapseArray.push(id);
        } else {
          this.collapseArray.splice(index, 1);
        }
        console.log("handSelect");
        console.log(this.collapseArray);
      },
      // 判断选中
      handleChange(data) {
        console.log("handleChange");
        console.log(data);
        this.$emit("sentDataToRoot", data)
      },
      reseverData(data) {
        console.log("下一层组件传上来的值");
        console.log(data);
      }
    },
    watch: {
      selectList(data) {
        console.log("watch");
        this.$props.change(data);
        this.selectList.concat(data);
        console.log(this.selectList);
      }
    }
  };
</script>
<style scoped>
  .treeRoot {
    list-style: none;
  }

  .treeNode {
    line-height: 24px;
    margin: 0;
    padding: 8px 20px;
    cursor: pointer;
    color: #666666;
  }

  .treeItem,
  .treeGroup {
    transition: background-color 0.5s;
  }

  .treeItem:hover,
  .treeGroup:hover {
    color: #333333;
    background-color: #e9e9e9;
  }

  .treeGroupContainer {
    min-height: 1px;
    overflow: hidden;
  }

  .treeCollaps {
    height: 0;
  }
</style>